package common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class StopWordFile {
  private Map stopWordMap = null;
  private IndexWordUtil wordUtil;
  private File stopWordFile;
  
  public StopWordFile(File stopWordFile, char[] breakChars) throws IOException {
    this.stopWordFile = stopWordFile;
    wordUtil = new IndexWordUtil(breakChars);
    parseStopFile(stopWordFile);
  }
  
  /**
   * Parse the stop words file. 
   */
  private void parseStopFile(File stopFile) throws IOException {
    stopWordMap = new HashMap();
    BufferedInputStream stopFileStream = null;
    try {
      stopFileStream = new BufferedInputStream(new FileInputStream(stopFile));
      
      for(String word = wordUtil.getNextWord(stopFileStream);
          word != null;
          word = wordUtil.getNextWord(stopFileStream)) {        
        stopWordMap.put(word.toLowerCase(), new Object());        
      }            
    }
    finally {
      if(stopFileStream != null) stopFileStream.close();
    }
  }
  
  public String getAbsolutePath() {
    return stopWordFile.getAbsolutePath();
  }

  /**
   * Returns true if <code>word</code> is a stop word, false otherwise
   * 
   * @param word Word to check stop words for
   * @return True if <code>word</code> is a stop word, false otherwise
   */
  public boolean isStopWord(String word) {
    return stopWordMap != null && stopWordMap.get(word) != null;
  }
}
